package app.models.booking;

import app.Const;
import app.models.sys.MerchantBrand;
import com.github.sog.annotation.TableBind;
import com.github.sog.config.StringPool;
import com.github.sog.controller.datatables.core.ColumnDef;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 餐饮预订记录
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-05-16 23:05
 * @since JDK 1.6
 */
@TableBind(tableName = "ol_dining_booking_record")
public class DiningRecord extends Model<DiningRecord> {

    private static final Logger logger           = LoggerFactory.getLogger(KtvProject.class);
    private static final long   serialVersionUID = 1L;

    public static DiningRecord dao = new DiningRecord();

    public long bookCount(long mid, long brandId, int tableCategory, String category, Date date) {
        return Db.queryLong(SqlKit.sql("diningbookingrecord.bookCount"), mid, brandId, tableCategory, category, date);
    }

    public long bookCountNoCategory(long mid, long brandId, int tableCategory, Date date) {
        return Db.queryLong(SqlKit.sql("diningbookingrecord.bookCountNoCategory"), mid, brandId, tableCategory, date);
    }

    public Page<Record> findByDateAndCodeAndPhone(String start, String end, String code, String phone, int page, MerchantBrand brand) {
        String where = SqlKit.sql("diningbookingrecord.columns-where-merchant") + " AND r.booking_date BETWEEN ? AND ? ";
        List<Object> params = Lists.newArrayListWithCapacity(3);
        params.add(start);
        params.add(end);
        if (!Strings.isNullOrEmpty(phone)) {
            where += " AND r.phone =? ";
            params.add(phone);
        }
        if (!Strings.isNullOrEmpty(code)) {

            where += " AND r.voucher =? ";
            params.add(code);
        }
        if (brand != null) {
            long brandId = brand.getNumber("brand").longValue();
            where += " AND r.brand = ? ";
            params.add(brandId);
        }
        final int page_size = 15;
        return Db.paginate(((page - 1) * page_size) + 1, page_size, SqlKit.sql("diningbookingrecord.findByDateAndCodeAndPhone"), where, params.toArray());
    }

    public long memberBookCount(long mid, long brandId, Date date) {
        return Db.queryLong(SqlKit.sql("diningbookingrecord.memberBookCount"), mid, brandId, date);
    }

    public void record(long mid, long brandId, int meal_num, String category, String name, String phone, Date date, int tableCategory, String voucher, boolean b) {
        DiningRecord diningBookingRecord = new DiningRecord();
        final Date now = new Date();
        diningBookingRecord.set("member", mid);
        diningBookingRecord.set("brand", brandId);
        diningBookingRecord.set("table_category", tableCategory);
        diningBookingRecord.set("booking_time", now);
        diningBookingRecord.set("voucher", voucher);
        diningBookingRecord.set("record_time", now);
        diningBookingRecord.set("status", Const.BOOKING_STATUS.STATUS_1);
        diningBookingRecord.set("notice", b);
        diningBookingRecord.set("meal_num", meal_num);
        diningBookingRecord.set("booking_date", date);
        diningBookingRecord.set("category", category);
        diningBookingRecord.set("name", name);
        diningBookingRecord.set("phone", phone);
        diningBookingRecord.save();
    }

    public long getCountByMid(long mid) {
        return Db.queryLong("select count(*) from ol_dining_booking_record where member=?", mid);
    }


    public List<DiningRecord> findByStusAndMid(int status, long mid) {
        return find(SqlKit.sql("diningbookingrecord.findByStusAndMid"), status, mid);
    }

    public Page<DiningRecord> datatable(DatatablesCriterias criterias,
                                        String brand, String voucher, String phone,
                                        String starttime, String endtime,
                                        int market, int category) {

        StringBuilder sb = new StringBuilder(" WHERE 1=1 ");

        List<Object> _params = Lists.newArrayList();


        if (!Strings.isNullOrEmpty(brand)) {
            sb.append(" AND booking.brand = ?");
            _params.add(brand);
        }

        if (!Strings.isNullOrEmpty(voucher)) {
            sb.append(" AND booking.voucher =  ? ");
            _params.add(voucher);
        }
        if (!Strings.isNullOrEmpty(phone)) {
            sb.append(" AND booking.phone = ?");
            _params.add(phone);
        }

        if (!Strings.isNullOrEmpty(starttime)) {
            sb.append(" AND booking.booking_time BETWEEN ? AND ?");
            _params.add(starttime);
            _params.add(StringUtils.defaultIfEmpty(endtime, starttime));
        }

        if(market > 0){
            sb.append(" AND booking.category =? ");
            _params.add(market);
        }

        if(category > 0){
            sb.append(" AND booking.table_category = ?");
            _params.add(category);
        }

        int pageSize = criterias.getDisplaySize();
        int start = criterias.getDisplayStart() / pageSize + 1;
        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();

        String where = SqlKit.sql("diningbookingrecord.columns-where") + sb.toString();

        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            final String byColumns = orderBy.toString();
            if (!Strings.isNullOrEmpty(byColumns)) {
                where += " ORDER BY " + byColumns;
            }
        }
        if (!where.contains("ORDER")) {
            where += " ORDER BY booking_date DESC";
        }

        return paginate(start, pageSize, SqlKit.sql("diningbookingrecord.columns-select"), where, _params.toArray());
    }

    public List<DiningRecord> findBookingListByMid(long mid) {
        return find(SqlKit.sql("diningbookingrecord.findBookingListByMid"), mid);
    }
}
